<template>
    <div class="pro-bindnum">
        <a-modal width="90%" :visible="visible" title="生产计划" @cancel="modalCancel" class="yuan-modal pro-bindnum-modal"
            :dialog-style="{ top: '20px' }">
            <a-spin tip="Loading..." :spinning="loading">
                <div class="yuan-container">
                    <div class="page-top">
                        <span class="page-title">{{detailInfo.materialName}}</span>
                        <span style="margin-left:20px">标准：{{detailInfo.standard}}</span>
                    </div>
                    <div class="page-main">
                        <div class="page-info-box">
                            <div class="page-info-list">
                                <div class="list-title">计划编号：</div>
                                <div class="list-info">{{detailInfo.planSerial}}</div>
                            </div>
                            <div class="page-info-list">
                                <div class="list-title">计划日期：</div>
                                <div class="list-info">{{detailInfo.finishTime | format('yyyy-MM-dd')}}</div>
                            </div>
                        </div>
                    </div>
                    <div class="page-main">
                        <div class="panel-title yuan-title">绑定批次号</div>
                        <a-card>
                            <a-tabs type="card" :activeKey="pageType" @change="tabChange">
                                <a-tab-pane v-for="item in typeArr" :key="item" :tab="item"></a-tab-pane>
                            </a-tabs>
                            <div class="planList-top">
                                <div class="yuan-title" style="padding:10px 0;margin-top:30px">
                                    生产数据
                                </div>
                                <template v-if="pageType!=='包装计划'">
                                    <div class="filter-panel">
                                        <div class="filter-list">
                                            <span class="filter-tips ">{{pageInfo.planName}}({{pageInfo.planSerial}})</span>
                                        </div>
                                        <div class="filter-list">
                                            <span class="filter-tips ">计划生产量：</span>
                                            <span class="font-bignum c-success">{{pageInfo.prodNum|toDecimalNoZero}}</span>
                                            <span>kg</span>
                                        </div>
                                        <div class="filter-list">
                                            <span class="filter-tips">预计投料数量：</span>
                                            <span class="font-bignum c-warning">{{pageInfo.inputNum|toDecimalNoZero}}</span>
                                            <span>kg</span>
                                        </div>
                                        <div class="filter-list">

                                            <span class="filter-tips ">
                                                {{getBatchName()}}批号：
                                                <span class="mast-ico"></span>
                                            </span>
                                            <a-input placeholder="请输入批号" v-model="pageData[pageType]" @input="batchChange" />
                                        </div>
                                    </div>
                                    <div class="table">

                                        <div class="yuan-title" style="padding:10px 0;margin-top:30px">
                                            {{pageInfo.materialType}}
                                        </div>
                                        <a-table bordered :rowKey="(row)=>row.id+row.batch" :data-source="pageList"
                                            :columns="columns" :pagination="false" :loading="loading">
                                        </a-table>

                                        <template v-if="accPageList.length>0">
                                            <div class="yuan-title" style="padding:10px 0;margin-top:50px">
                                                辅料
                                            </div>
                                            <a-table bordered :rowKey="(row)=>row.id" :data-source="accPageList"
                                                :columns="accColumns" :pagination="false" :loading="loading"
                                                v-if="accPageList.length>0">
                                            </a-table>
                                        </template>

                                    </div>
                                </template>
                                <template v-else>
                                    <div style="border:solid 1px #eee;background-color:#f6f6f6;margin-bottom:20px"
                                        v-for="item in planList">
                                        <div class="filter-panel">
                                            <div class="filter-list">
                                                <span class="filter-tips ">包装计划（{{item.planSerial}}）</span>
                                            </div>
                                            <div class="filter-list">
                                                <span class="filter-tips ">产品大类：{{item.inventoryType}}</span>
                                            </div>
                                            <div class="clear-both"></div>
                                            <div class="filter-list">
                                                <span class="filter-tips ">{{item.materialName}}</span>
                                            </div>
                                            <div class="filter-list">
                                                <span class="filter-tips ">计划包装量：</span>
                                                <span class="font-bignum c-success">{{item.prodNum|toDecimalNoZero}}</span>
                                                <span>袋</span>
                                            </div>
                                            <div class="filter-list">
                                                <span class="filter-tips ">{{item.materialType}}投料量：</span>
                                                <span class="font-bignum c-success">{{item.inputNum|toDecimalNoZero}}</span>
                                                <span>kg</span>
                                            </div>
                                            <div class="filter-list">
                                                <span class="filter-tips">{{getBatchName()}}批号：<span
                                                        class="mast-ico"></span></span>
                                                <a-input placeholder="请输入批号" v-model="item.finishedBatch"
                                                    @input="bzBatchChange" />
                                            </div>
                                        </div>
                                        <div class="table">
                                            <div class="yuan-title" style="padding:10px 0;margin-top:30px">
                                                {{pageInfo.materialType}}
                                            </div>
                                            <a-table bordered :rowKey="(row)=>row.id+row.batch"
                                                :data-source="pageListBz[item.inventoryType]" :columns="columns"
                                                :pagination="false" :loading="loading">
                                            </a-table>
                                        </div>
                                    </div>

                                </template>

                            </div>

                        </a-card>
                    </div>
                </div>

            </a-spin>
            <template slot="footer">
                <a-button type="primary" @click="clickSave" :loading="loading">
                    确认绑定
                </a-button>
                <a-button @click="modalCancel">
                    关闭
                </a-button>
            </template>
        </a-modal>
    </div>
</template>

<script lang="ts">
import warningApi from "@/api/warningApi";
import { toDecimalNoZero } from "@/utils";
import { Vue, Component, Prop, Watch } from "vue-property-decorator";

@Component({ name: "TPL", components: {} })
export default class index extends Vue {
    @Prop({ default: "" }) visible!: boolean;
    @Prop({ default: "" }) id!: string;
    @Watch("visible")
    visibleChange() {
        if (this.visible) {
            this.getDetailInfo();
        }
    }
    pageType = "";
    detailInfo: any = {};
    loading = false;
    pageData = {};
    closeModal() {
        this.$emit("closeModal");
    }
    modalCancel() {
        this.closeModal();
    }

    processPlanDetailList: any[] = [];
    pageList: any[] = [];
    async getDetailInfo() {
        this.loading = true;
        try {
            const res = await warningApi.getPlanDetial({ id: this.id });
            this.detailInfo = res.data || {};
            this.processPlanDetailList = this.detailInfo.processPlanDetailList;
            let typeArr = this.processPlanDetailList.map((item) => {
                return item.planName;
            });

            typeArr = Array.from(new Set(typeArr));
            typeArr.reverse();
            this.typeArr = typeArr;
            this.pageType = typeArr[0];
            this.getPageList();
        } finally {
            this.loading = false;
        }
    }
    typeArr: string[] = [];
    pageInfo = {};
    accPageList: any[] = [];
    planList: any[] = [];
    pageListBz = {};
    getPageList() {
        if (this.pageType === "包装计划") {
            const planList = JSON.parse(this.detailInfo.planList || "");
            const filterList = this.processPlanDetailList.filter((item) => {
                return item.planName === "包装计划";
            });
            filterList.forEach((item) => {
                planList.forEach((plan, index) => {
                    if (plan.inventoryType === item.inventoryType) {
                        planList[index] = {
                            ...plan,
                            planSerial: item.planSerial,
                            materialName: item.materialName,
                            prodNum: item.prodNum,
                        };
                    }
                });
            });
            this.planList = planList;
            let pageListBz = {};
            filterList.forEach((item) => {
                pageListBz[item.inventoryType] = item.processPlanInputList.filter((item)=>{
                    return !!item.batch
                });
            });
            this.pageListBz = pageListBz;
            this.pageInfo = {};
            this.accPageList = [];
        } else {
            const find = this.processPlanDetailList.find((item) => item.planName === this.pageType);

            if (find) {
                const pageList: any[] = [];
                const accPageList: any[] = [];
                const processPlanInputList = find.processPlanInputList;
                processPlanInputList.forEach((item) => {
                    if (item.materialType === "辅料") {
                        accPageList.push(item);
                    } else if (item.batch) {
                        pageList.push(item);
                    }
                });
                this.pageInfo = find;
                this.pageList = pageList;
                this.accPageList = accPageList;
            } else {
                this.pageInfo = {};
                this.pageList = [];
                this.accPageList = [];
            }
        }
    }
    tabChange(e: string) {
        this.pageType = e;
        this.getPageList();
    }
    accColumns = [
        {
            align: "center",
            dataIndex: "materialName",
            key: "materialName",
            title: "投料名称",
        },
        {
            align: "center",
            dataIndex: "inputNum",
            key: "inputNum",
            title: "投料数量(kg)",
            customRender: (text: string, record: any, index: number) => toDecimalNoZero(record.inputNum),
        },
    ];
    columns: any[] = [
        {
            align: "center",
            dataIndex: "batch",
            key: "batch",
            title: "投料批次",
        },
        {
            align: "center",
            dataIndex: "isPro",
            key: "isPro",
            title: "投料状态",
            customRender: (text: string, record: any, index: number) =>
                record.isPro === "true" ? "计划生产投料" : "现有库存投料",
        },
        {
            align: "center",
            dataIndex: "materialName",
            key: "materialName",
            title: "投料名称",
        },
        {
            align: "center",
            dataIndex: "inputNum",
            key: "inputNum",
            title: "实际投料数量(kg)",
            customRender: (text: string, record: any, index: number) => toDecimalNoZero(record.inputNum),
        },
    ];
    getBatchName() {
        const data = {
            包装计划: "成品",
            制剂计划: "颗粒（颗粒）",
            提取计划: "提取物",
            饮片计划: "饮片",
        };
        return data[this.pageType];
    }
    simulationTimer: number | null = null;
    bzBatchChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        this.simulationTimer = setTimeout(async () => {
            this.planList.forEach((item) => {
                const plan = this.processPlanDetailList.find((detail) => {
                    return detail.inventoryType === item.inventoryType;
                });
                plan.batch = item.finishedBatch;
            });
        }, 500);
    }
    batchChange() {
        // 加个防抖
        if (this.simulationTimer) {
            clearTimeout(this.simulationTimer);
        }
        this.simulationTimer = setTimeout(async () => {
            const data = {
                包装计划: "",
                制剂计划: "包装计划",
                提取计划: "制剂计划",
                饮片计划: "提取计划",
            };
            const nextPlanName = data[this.pageType];
            const nowPlan = this.processPlanDetailList.find((item) => {
                return item.planName === this.pageType;
            });
            if (nowPlan) {
                nowPlan.batch = this.pageData[this.pageType];
            }
            if (this.pageType === "制剂计划") {
                const filterList = this.processPlanDetailList.filter((item) => {
                    return item.planName === nextPlanName;
                });
                filterList.forEach((item) => {
                    // 清空之前的添加的数据
                    item.processPlanInputList = item.processPlanInputList.filter((item) => {
                        return item.id !== "";
                    });

                    if (item.needNum > 0 && this.pageData[this.pageType]) {
                        const tpl = item.processPlanInputList[0];
                        item.processPlanInputList.push({
                            ...tpl,
                            isPro: "true",
                            batch: this.pageData[this.pageType],
                            id: "",
                            inputNum: item.needNum,
                        });
                    }
                });
            } else {
                let nextPlan = this.processPlanDetailList.find((item) => {
                    return item.planName === nextPlanName;
                });
                const tpl = nextPlan.processPlanInputList[0];
                // 清空之前的添加的数据
                nextPlan.processPlanInputList = nextPlan.processPlanInputList.filter((item) => {
                    return item.id !== "";
                });
                if (this.pageData[this.pageType]) {
                    nextPlan.processPlanInputList.push({
                        ...tpl,
                        isPro: "true",
                        batch: this.pageData[this.pageType],
                        id: "",
                        inputNum: nextPlan.needNum,
                    });
                }
            }
        }, 500);
    }

    async clickSave() {
        if (!this.pageData["饮片计划"] && this.typeArr.indexOf("饮片计划") >= 0) {
            this.$message.error("饮片批号还没有输入");
            return false;
        }
        if (!this.pageData["提取计划"] && this.typeArr.indexOf("提取计划") >= 0) {
            this.$message.error("提取物批号还没有输入");
            return false;
        }
        if (!this.pageData["制剂计划"] && this.typeArr.indexOf("制剂计划") >= 0) {
            this.$message.error("颗粒（颗粒）批号还没有输入");
            return false;
        }

        let type = true;
        this.planList.forEach((item) => {
            if (Number(item.prodNum) >= 0 && !item.finishedBatch) {
                this.$message.error("成品批号：" + item.inventoryType + "还没有输入");
                type = false;
            }
        });
        if (!type) return false;

        this.loading = true;
        try {
            const res = await warningApi.postBindBatch({
                ...this.detailInfo,
                planList: JSON.stringify(this.planList),
                processPlanDetailList: this.processPlanDetailList,
            });
            this.$message.success(res.msg);
            this.closeModal();
            this.$emit("resetList");
        } finally {
            this.loading = false;
        }
    }
}
</script>

<style lang="scss">
.pro-bindnum-modal {
    .page-top {
        padding-bottom: 20px;
        border-bottom: solid 1px #eee;
    }
    .page-title {
        font-weight: bold;
        font-size: 20px;
    }
    .page-main {
        background-color: #fff;
        border-radius: 10px;
        padding: 20px;
        margin-bottom: 20px;
    }
    .page-info-list {
        display: inline-flex;
        margin-right: 20px;
    }
    .panel-title {
        font-size: 16px;
        padding-bottom: 10px;
    }
    .planList-top {
        margin-bottom: 20px;
    }
    .table {
        background-color: #fff;
    }
}
</style>
